package com.face.server.communication.mina;

import com.face.server.common.utils.log.Logs;
import com.face.server.communication.mina.config.MinaConfig;
import com.face.server.communication.mina.factory.ByteArrayCodecFactory;
import com.face.server.communication.mina.handlers.MinaServerHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yangzhongming
 * @desc 人脸识别出纸机--mina 服务端启动类
 * @date 2022/1/24
 */
@Component
public class MinaServer {

    private static final Logger logger = Logs.get();

    @Autowired
    private MinaServerHandler minaServerHandler;
    @Autowired
    private MinaConfig config;

    private NioSocketAcceptor acceptor;

    /**
     * 30秒后超时
     */
    private static final int IDELTIMEOUT = 30;
    /**
     * 15秒发送一次心跳包
     */
    private static final int HEARTBEATRATE = 15;
    /**
     * 心跳包内容
     */
    private static final String HEARTBEATREQUEST = "0x11";
    private static final String HEARTBEATRESPONSE = "0x12";

    /**
     * 启动连接监听
     */
    public void start() {
        try {
            acceptor = new NioSocketAcceptor();
            acceptor.setHandler(minaServerHandler);
            acceptor.getFilterChain().addLast("serverCoder", new ProtocolCodecFilter(new ByteArrayCodecFactory()));

            ExecutorService executorService = Executors.newFixedThreadPool(5);

//            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 30L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
            acceptor.getFilterChain().addLast("executor",
                    new ExecutorFilter(executorService));

            acceptor.getSessionConfig().setKeepAlive(true);
            acceptor.getSessionConfig().setSoLinger(0);
            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, config.getServerIdleTime());
            acceptor.bind(new InetSocketAddress(config.getServerPort()));
            logger.info("服务启动完毕......");
            logger.info("监听端口：{}", config.getServerPort());

        } catch (Exception e) {
            logger.error("服务启动出错", e);
            e.printStackTrace();
        }
        //开启数据分析模块
//        executorService.execute(new CollectModel());
    }

    public void close() {
        try {
            acceptor.dispose();
            logger.info("服务关闭完毕......");
        } catch (Exception e) {
            logger.error("服务关闭出错", e);
        }
    }
}
